package com.example.springcaptcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.example.springcaptcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final static long SESSION_VALID_TIMEOUT = 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response,HttpSession  session) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");

        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        lineCaptcha.setGenerator(randomGenerator);
        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
        session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(), new Date());
    }


    @RequestMapping("/verify")
    public boolean verify(String inputCaptcha, HttpSession session)  {
        System.out.println(inputCaptcha);
        if (!StringUtils.hasLength(inputCaptcha)) {
            return false;
        }
        String captchaCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date captchaDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        System.out.println(captchaDate);
        if (inputCaptcha.equalsIgnoreCase(captchaCode)) {
            if (captchaDate != null && System.currentTimeMillis() - captchaDate.getTime() < SESSION_VALID_TIMEOUT) {}
            return true;
        }
        return false;
    }


}
